<?php

/*
 * Copyright (C) 2020 Karam Assany <karam.assany@tuta.io>
 * Licensed under the MIT (Expat) license
 */

$token = getenv('BOT_TOKEN');
$username = getenv('USER_NAME');

$message = json_decode(file_get_contents('php://input'), true)['message'];

function api_call($method, $params)
{
    global $token;

    $url = "https://api.telegram.org:443/bot$token/$method";

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params));
    $response = curl_exec($curl);
    curl_close($curl);

    return json_decode($response, true);
};

function promote($chat_id, $user_id)
{
    api_call('promoteChatMember', array(
            'chat_id' => $chat_id,
            'user_id' => $user_id,
            'can_change_info' => true,
            'can_delete_messages' => true,
            'can_invite_users' => true,
            'can_restrict_members' => true,
            'can_pin_messages' => true,
            'can_promote_members' => true
    ));
};

if ($message['chat']['type'] == 'private')
{
    $text = "This bot works only in groups, just add it in a group and give it full"
    ." admin permissions:\nhttps://t.me/$username?startgroup=true\n\n"
    ."Source code:\nhttps://notabug.org/karam/groupanarchy";

    api_call('sendMessage', array(
            'chat_id' => $message['chat']['id'],
            'text' => $text,
            'disable_web_page_preview' => true
        ));
};

if ($message['chat']['type'] == 'supergroup')
{
    $text = strtolower($update['message']['text']);
    $chat_id = $message['chat']['id'];

    if ( ($text == "/enforce")
         or ($text == strtolower("/enforce@$username")) )
    {
        promote($chat_id, $message['from']['id']);
        promote($chat_id, $message['reply_to_message']['from']['id']);
    };

    foreach ($message['new_chat_members'] as $member) {
        promote($chat_id, $member['id']);
    };
};
